//
//  DCommonTool.m
//  DFrame
//
//  Created by DaiSuke on 16/8/29.
//  Copyright © 2016年 DaiSuke. All rights reserved.
//

#import "DCommonTool.h"
#import "DCacheManager.h"
#import <AudioToolbox/AudioToolbox.h>

@implementation DCommonTool

/**
 *  获取到颜色UICOLOR
 *
 *  @param hexColor “987567”
 *
 *  @return UIColor*
 */
+ (UIColor *)TColor:(NSString *)hexColor
{
    return [DCommonTool TColor:hexColor colorAlpha:1.0];
}

/**
 *  获取到颜色UICOLOR
 *
 *  @param hexColor “987567”
 *  @param alpha    0 ~ 1
 *
 *  @return UIColor
 */
+ (UIColor *)TColor:(NSString *)hexColor colorAlpha:(CGFloat)alpha
{
    NSAssert(hexColor, @"获取到颜色UICOLOR -->hexColor not be nil");
    
    NSString *cString = [[hexColor stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]){
        cString = [cString substringFromIndex:2];
    }else if ([cString hasPrefix:@"#"]){
        cString = [cString substringFromIndex:1];
    }else if ([cString length] != 6){
        return [UIColor clearColor];
    }
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:alpha];
}

/**
 *  当然线程是否是主线程
 *
 *  @return YES主线程 | NO 子线程
 */
+ (BOOL)cureentThreadIsMain
{
    return [[NSThread currentThread] isMainThread];
}

/**
 *  十六进制字符串转换为数值
 *
 *  @param hexString 十六进制字符串
 *
 *  @return 对于的数值
 */
+ (unsigned long)longNumberFromHexString:(NSString *)hexString
{
    NSAssert(hexString, @"longNumberFromHexString -> hexString not be nil");
    //   strtoul(const char *nptr,char **endptr,int base);会将参数nptr字符串根据参数base来转换成无符号的长整型数。
    return strtoul([hexString UTF8String],0,0);
}


/**
 *  十六进制转换为普通字符串
 *
 *  @param hexString 十六进制字符串
 *
 *  @return 普通字符串
 */
//+ (NSString *)stringFromHexString:(NSString *)hexString
//{
//    NSAssert(hexString, @"stringFromHexString -> hexString not be nil");
//    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
//    bzero(myBuffer, [hexString length] / 2 + 1);
//    for (int i = 0; i< [hexString length] - 1; i += 2) {
//        @autoreleasepool {
//            unsigned int anInt;
//            NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
//            NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
//            [scanner scanHexInt:&anInt];
//            myBuffer[i / 2] = (char)anInt;
//        }
//    }
//   return [NSString stringWithCString:myBuffer encoding:NSUTF8StringEncoding];
//}

/**
 *  普通字符串成转换为十六进制字符串
 *
 *  @param hexString 普通字符串
 *
 *  @return 十六进制字符串
 */
+ (NSString *)hexStringFromString:(NSString *)string
{
    NSAssert(string, @"hexStringFromString -> string not be nil");
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    NSString *hexStr = nil;
    for(int i=0;i<[myD length];i++)  {
        @autoreleasepool {
            NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];//16进制数
            if([newHexStr length] == 1){
                hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
            } else{
                hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
            }
        }
    }
    return hexStr;
}

//data 转int
+ (int)intNumberFromData:(NSData *)data
{
    NSAssert(data, @"intNumberFromData -> data not be nil");
    int i = -1;
    [data getBytes:&i length:sizeof(i)];
    return i;
}

//int 转data
+ (NSData *)dataFromInt:(int)aNumber
{
    return [NSData dataWithBytes:&aNumber length:sizeof(aNumber)];
}


/**
 判断数字
 
 @param string
 @return
 */
+ (BOOL)isHasNum:(NSString *)string{
    NSString * regex = @"^[0-9]$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}


//是否包含表情字符
+ (BOOL)isContainsEmoji:(NSString *)string
{
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     isEomji = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 isEomji = YES;
             }
         } else {
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 isEomji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 isEomji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 isEomji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 isEomji = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                 isEomji = YES;
             }
         }
     }];
    return isEomji;
}


/**
 *  计算指定时间与当前的时间差
 *
 *  @param compareDateString  时间字符串(格式:2013-3-2 8:28:53)
 *
 *  @return (比如，3分钟前，1个小时前，2015年1月10日)
 *
 *  ADD BY ZHANGZH
 */
+ (NSString *)compareCurrentTime:(NSString *)compareDateString
{
    
    if(compareDateString.length > 23){
        compareDateString = [compareDateString substringToIndex:23];
    }
    
    //把时间字符串转化为NSDate
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
    NSDate *compareDate = [formatter dateFromString:compareDateString];
    if(compareDate==nil)
    {
        [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
        compareDate= [formatter dateFromString:compareDateString];;
    }
    
    NSTimeInterval timeInterval=[compareDate timeIntervalSinceNow];
    timeInterval=-timeInterval;
    long temp=0;
    NSString *compareResult;
    if(timeInterval<60)
    {
        compareResult=[NSString stringWithFormat:@"1分钟前"];
    }
    else if((temp=timeInterval/60)<60)
    {
        compareResult=[NSString stringWithFormat:@"%i分钟前",(int)temp];
    }
    else if((temp=temp/60)<24)
    {
        compareResult=[NSString stringWithFormat:@"%i小时前",(int)temp];
    }
    //    else if((temp=temp/24)<30)
    //    {
    //        [formatter setDateFormat:@"MM-dd HH:mm"];
    //        compareResult=[formatter stringFromDate:compareDate];
    //    }
    //    else if((temp=temp/30)<12)
    //    {
    //        [formatter setDateFormat:@"MM-dd"];
    //        compareResult=[formatter stringFromDate:compareDate];
    //    }
    else
    {
        //        temp=temp/12;
        //        [formatter setDateFormat:@"yyyy-MM-dd"];
        compareResult = @"一天前";
    }
    return compareResult;
}

//格式话小数 四舍五入类型 “0.000”
+ (NSString *) decimalwithFormat:(NSString *)format  numberValue:(NSNumber *)numberValue
{
    float value = [numberValue floatValue];
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    
    [numberFormatter setPositiveFormat:format];
    
    return  [numberFormatter stringFromNumber:[NSNumber numberWithFloat:value]];
}

/**
 *  获取带间距内容的文本size
 *
 *  @param content  全部内容
 *  @param font     字体
 *  @param maxWidth 最大宽大
 *
 *  @return 文本size
 */
+ (CGSize)getContentSizeForHasLineSpaceByContent:(NSString *)content font:(UIFont *)font maxWidth:(CGFloat)maxWidth{
    CGSize sizeContent = [content sizeWithFont:font maxWidth:maxWidth];
    NSString *strSize = @"擦";
    CGSize size = [strSize sizeWithFont:font maxWidth:maxWidth];
    if(size.height > 0){
        sizeContent.height += (sizeContent.height/size.height - 1) * 5;
    }
    return sizeContent;
}

/**
 *  获取带间距内容的文本
 *
 *  @param content 全部内容
 *
 *  @return 组装后的文本
 */
+ (NSAttributedString *)getAttrLineSpaceForContent:(NSString *)content{
    if(!IOS6 || content.length == 0){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
    [lineStyle setLineSpacing:5.0];
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
    
    return attributeStr;
}

/**
 *  为内容添加下划线
 *
 *  @param content 内容
 *
 *  @return 组装后的文本
 */
+ (NSAttributedString *)getAttrDownLineForContent:(NSString *)content{
    if(!IOS6 || content.length == 0){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    NSRange contentRange = {0, [content length]};
    [attributeStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:contentRange];
    return attributeStr;
}

/**
 *  为内容添加下划线
 *
 *  @param content 内容
 *
 *  @return 组装后的文本
 */
+ (NSAttributedString *)getAttrDownLineForContent:(NSString *)content keyword:(NSString *)keyword keywordColor:(UIColor *)color{
    if(!IOS6 || content.length == 0){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    
    NSRange range = [content rangeOfString:keyword];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)color range:range];
    if(IOS8){
        [attributeStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:range];
    }
    return attributeStr;
}

/**
 *  获取内容的文本带高亮背景
 *
 *  @param keyword 高亮背景部分内容
 *  @param content 全部内容
 *  @param color   高亮的颜色
 *
 *  @return 组装后的文本
 */
+ (NSAttributedString *)getAttrForBGByKeyWord:(NSString *)keyword content:(NSString *)content heightLightColor:(UIColor *)color{
    if(!IOS6 || content.length == 0){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    NSRange range = [content rangeOfString:keyword];
    [attributeStr addAttribute:NSBackgroundColorAttributeName value:(id)color range:range];
    return attributeStr;
}

/**
 *  获取带高亮内容的文本
 *
 *  @param keyword 高亮部分内容
 *  @param content 全部内容
 *  @param color   高亮的颜色
 *
 *  @return 组装后的文本
 */
+ (NSAttributedString *)getAttrByKeyWord:(NSString *)keyword content:(NSString *)content heightLightColor:(UIColor *)color{
    if(!IOS6){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    NSRange range = [content rangeOfString:keyword];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)color range:range];
    NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
    [lineStyle setLineSpacing:5.0];
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
    
    return attributeStr;
}

/**
 *  获取带高亮内容的文本
 *
 *  @param keywords 高亮部分内容(数组)
 *  @param content 全部内容
 *  @param color   高亮的颜色
 *
 *  @return 组装后的文本
 */
+ (NSAttributedString *)getAttrByKeyWords:(NSArray *)keywords content:(NSString *)content heightLightColor:(UIColor *)color{
    if(!IOS6){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    
    for (NSString *keyword in keywords.objectEnumerator) {
        NSRange range = [content rangeOfString:keyword];
        [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)color range:range];
    }
    NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
    [lineStyle setLineSpacing:5.0];
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
    
    return attributeStr;
}

/**
 *  获取带高亮内容的文本
 *
 *  @param keyword      高亮部分内容
 *  @param content      全部内容
 *  @param keywordColor 高亮的颜色
 *  @param contentColor 其余部分的颜色
 *  @param keyWordFont  高亮内容字体
 *  @param contentFont  其余部分字体
 *
 *  @return 组装后的文本
 */
+ (NSAttributedString *)getAttrSpaceByKeyWord:(NSString *)keyword content:(NSString *)content keywordColor:(UIColor *)keywordColor contentColor:(UIColor *)contentColor keywordFont:(UIFont *)keyWordFont contentFont:(UIFont *)contentFont{
    if(!IOS6){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    NSRange range = [content rangeOfString:keyword];
    
    NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
    [lineStyle setLineSpacing:5.0];
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
    [attributeStr addAttribute:NSFontAttributeName value:(id)contentFont range:NSMakeRange(0, content.length)];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)contentColor range:NSMakeRange(0, content.length)];
    
    [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)keywordColor range:range];
    [attributeStr addAttribute:NSFontAttributeName value:(id)keyWordFont range:range];
    
    
    return attributeStr;
}

+ (NSAttributedString *)getAttrSpaceByKeyWord1:(NSString *)keyword1 keyWord2:(NSString *)keyword2 content:(NSString *)content keyword1Color:(UIColor *)keyword1Color keyword2Color:(UIColor *)keyword2Color{
    if(!IOS6 || content.length == 0){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    
    NSRange range1 = [content rangeOfString:keyword1];
    NSRange range2 = [content rangeOfString:keyword2];
    NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
    [lineStyle setLineSpacing:5.0];
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)keyword1Color range:range1];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)keyword2Color range:range2];
    
    
    return attributeStr;
}

/**
 *  获取带高亮内容的文本
 *
 *  @param keywords 高亮部分内容(数组)
 *  @param content 全部内容
 *  @param color   高亮的颜色
 *  @param indent  首行缩进
 *
 *  @return 组装后的文本
 */
+ (NSAttributedString *)getAttrByKeyWords:(NSArray *)keywords content:(NSString *)content heightLightColor:(UIColor *)color indent:(CGFloat)indent{
    if(!IOS6){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    
    for (NSString *keyword in keywords.objectEnumerator) {
        NSRange range = [content rangeOfString:keyword];
        [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)color range:range];
    }
    NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
    [lineStyle setLineSpacing:5.0];
    [lineStyle setFirstLineHeadIndent:indent];
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
    
    return attributeStr;
}


/**
 *  获取带高亮内容的文本
 *
 *  @param keyword 高亮部分内容
 *  @param content 全部内容
 *  @param color   高亮的颜色
 *
 *  @return 组装后的文本
 */
+ (NSAttributedString *)getAttrNotSpaceByKeyWord:(NSString *)keyword content:(NSString *)content heightLightColor:(UIColor *)color{
    if(!IOS6){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    if(content.length > 0 && keyword.length == 0){
        NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
        [lineStyle setLineSpacing:0.0];
        [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
    }
    else{
        
        NSRange range = [content rangeOfString:keyword];
        [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)color range:range];
        NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
        [lineStyle setLineSpacing:0.0];
        [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
        [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)color range:range];
    }
    
    
    
    return attributeStr;
}

/**
 *  获取带高亮内容的文本
 *
 *  @param keyword 高亮部分内容
 *  @param content 全部内容
 *  @param color   高亮的颜色
 *
 *  @return 组装后的文本
 */
+ (NSAttributedString *)getAttrNotSpaceByKeyWord:(NSString *)keyword content:(NSString *)content heightLightColor:(UIColor *)color keywordBgColor:(UIColor *)keyworBgColor{
    if(!IOS6){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    NSRange range = [content rangeOfString:keyword];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)color range:range];
    NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
    [lineStyle setLineSpacing:0.0];
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)color range:range];
    [attributeStr addAttribute:NSBackgroundColorAttributeName value:(id)keyworBgColor range:range];
    
    
    return attributeStr;
}


/**
 *  获取带高亮内容的文本
 *
 *  @param keyword 高亮部分内容
 *  @param content 全部内容
 *  @param color   高亮的颜色
 *
 *  @return 组装后的文本
 */
+ (NSAttributedString *)getAttrNotSpaceByKeyWords:(NSArray *)keywords content:(NSString *)content heightLightColor:(UIColor *)color{
    if(!IOS6){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
    [lineStyle setLineSpacing:0.0];
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
    for (NSString *keyword in keywords.objectEnumerator) {
        NSRange range = [content rangeOfString:keyword];
        [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)color range:range];
    }
    
    return attributeStr;
}

+ (NSAttributedString *)getAttrNotSpaceByKeyWord1:(NSString *)keyword1 keyWord2:(NSString *)keyword2 content:(NSString *)content keyword1Color:(UIColor *)keyword1Color keyword2Color:(UIColor *)keyword2Color{
    if(!IOS6 || content.length == 0){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    NSRange range1 = [content rangeOfString:keyword1];
    NSRange range2 = [content rangeOfString:keyword2];
    NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
    [lineStyle setLineSpacing:0.0];
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)keyword1Color range:range1];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)keyword2Color range:range2];
    
    
    return attributeStr;
}

/**
 *  获取带高亮内容的文本
 *
 *  @param keyword      高亮部分内容
 *  @param content      全部内容
 *  @param keywordColor 高亮的颜色
 *  @param contentColor 其余部分的颜色
 *  @param keyWordFont  高亮内容字体
 *  @param contentFont  其余部分字体
 *
 *  @return 组装后的文本
 */
+ (NSAttributedString *)getAttrNotSpaceByKeyWord:(NSString *)keyword content:(NSString *)content keywordColor:(UIColor *)keywordColor contentColor:(UIColor *)contentColor keywordFont:(UIFont *)keyWordFont contentFont:(UIFont *)contentFont{
    if(!IOS6){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    NSRange range = [content rangeOfString:keyword];
    
    NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
    [lineStyle setLineSpacing:0.0];
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
    [attributeStr addAttribute:NSFontAttributeName value:(id)contentFont range:NSMakeRange(0, content.length)];
    [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)contentColor range:NSMakeRange(0, content.length)];
    
    [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)keywordColor range:range];
    [attributeStr addAttribute:NSFontAttributeName value:(id)keyWordFont range:range];
    
    
    return attributeStr;
}

/**
 *  获取带高亮内容的文本
 *
 *  @param keywords 高亮部分内容(数组)
 *  @param content 全部内容
 *  @param color   高亮的颜色
 *  @param keyWordFont  高亮内容字体
 *
 *  @return 组装后的文本
 */
+ (NSAttributedString *)getAttrByKeyWords:(NSArray *)keywords content:(NSString *)content heightLightColor:(UIColor *)color keywordFont:(UIFont *)keyWordFont{
    if(!IOS6){
        return nil;
    }
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
    
    for (NSString *keyword in keywords.objectEnumerator) {
        NSRange range = [content rangeOfString:keyword];
        [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)color range:range];
        [attributeStr addAttribute:NSFontAttributeName value:keyWordFont range:range];
    }
    NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
    [lineStyle setLineSpacing:5.0];
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
    
    return attributeStr;
}

///**
// *  获取带高亮内容的文本
// *
// *  @param keywords 高亮部分内容(数组)
// *  @param content 全部内容
// *  @param color   高亮的颜色
// *  @param keyWordFont  高亮内容字体
// *
// *  @return 组装后的文本
// */
//+ (NSAttributedString *)getAttrByHasOrderKeyWords:(NSArray *)keywords content:(NSString *)content heightLightColor:(UIColor *)color keywordFont:(UIFont *)keyWordFont{
//    if(!IOS6){
//        return nil;
//    }
//    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:content];
//
//    NSString *strContent = content;
//    for (NSString *keyword in keywords.objectEnumerator) {
//        NSRange range = [strContent rangeOfString:keyword];
//
//        [attributeStr addAttribute:NSForegroundColorAttributeName value:(id)color range:range];
//        [attributeStr addAttribute:NSFontAttributeName value:keyWordFont range:range];
//    }
//    NSMutableParagraphStyle *lineStyle = [[NSMutableParagraphStyle alloc] init];
//    [lineStyle setLineSpacing:5.0];
//    [attributeStr addAttribute:NSParagraphStyleAttributeName value:lineStyle range:NSMakeRange(0, content.length)];
//
//    return attributeStr;
//}


/**
 *  获取带****的手机号码
 *
 *  @param mobile 原手机号码
 *
 *  @return 带****的手机号码
 */
+ (NSString *)getSubMobile:(NSString *)mobile{
    NSMutableString *strMobile = [NSMutableString new];
    [strMobile appendString:[mobile substringToIndex:3]];
    [strMobile appendString:@"****"];
    [strMobile appendString:[mobile substringFromIndex:7]];
    return strMobile;
}

/**
 *  判断是否为汉字
 *
 *  @param content 字符串
 *
 *  @return NO代表字符串包含不是汉字的字符，YES代表全部为汉字
 */
+ (BOOL)isChinese:(NSString *)content
{
    if(content && content.length > 0)
    {
        for (int index=0; index<content.length; index++)
        {
            NSRange range=NSMakeRange(index, 1);
            
            NSString *subString=[content substringWithRange:range];
            
            const char *cString=[subString UTF8String];
            
            if(!cString || strlen(cString)==1)
            {
                return NO;
            }
        }
        return YES;
        
    }
    else
    {
        return NO;
    }
    
}

/**
 *  判断是否只包含字母和数字,并且是6-20位数
 *
 *  @param content 字符串
 *
 *  @return NO代表不符合条件，YES代表符合条件
 */
+ (BOOL)isPassWord:(NSString *)content
{
    if(content.length>0)
    {
        NSString *regex=@"[0-9a-zA-Z]{6,20}";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        if([predicate evaluateWithObject:content]==YES)
        {
            return YES;
        }
        else
        {
            return NO;
        }
        
    }
    else
    {
        return NO;
    }
}


+ (NSString *)stringFromArray:(NSArray * )sources key:(NSString *)key isAdd:(BOOL)isAdd
{
    if (!sources || !key) {
        return nil;
    }
    //    NSMutableString * jsonStr = [[NSMutableString alloc] initWithString:@"["];
    NSMutableString * jsonStr = [[NSMutableString alloc] init];
    
    for (int i = 0;i <sources.count;i++) {
        id upid = [sources objectAtIndex:i];
        if ([upid isKindOfClass:[NSString class]]){
            if (isAdd) {
                [jsonStr appendFormat:@"%@=\"%@\"",key,upid];
            }else{
                [jsonStr appendFormat:@"%@=%@",key,upid];
            }
        }else{
            [jsonStr appendFormat:@"%@=%@",key,[upid description]];
        }
        
        if (i != sources.count - 1) {
            [jsonStr appendString:@"&"];
        }
    }
    
    //    [jsonStr appendFormat:@"]"];
    return jsonStr;
}

//+ (NSString *)getNavigationBarRightTitleByType:(ZKBNavigationItemType)type{
//    NSString *strTitle = @"";
//    switch (type) {
//        case ZKBNavigationItemTypeRightHome:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_HOME;
//            break;
//        }
//        case ZKBNavigationItemTypeRightSend:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_SEND;
//            break;
//        }
//        case ZKBNavigationItemTypeRightSave:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_SAVE;
//            break;
//        }
//        case ZKBNavigationItemTypeRightCreateProject:{
//            strTitle=ZKB_NAVIGATION_BAR_TEXT_RIGHT_CREATEPROJECT;
//            break;
//        }
//        case ZKBNavigationItemTypeRightNewProject:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_NEWPROJECT;
//            break;
//        }
//        case ZKBNavigationItemTypeRightSubscribeProject:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_SUBSCRIBE;
//            break;
//        }
//        case ZKBNavigationItemTypeRightClear:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_CLEAR;
//            break;
//        }
//        case ZKBNavigationItemTypeRightNext:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_NEXT;
//            break;
//        }
//        case ZKBNavigationItemTypeRightManager:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_MANAGER;
//            break;
//        }
//        case ZKBNavigationItemTypeRightRead:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_READ;
//            break;
//        }
//        case ZKBNavigationItemTypeRightPublic:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_PUBLIC;
//            break;
//        }
//        case ZKBNavigationItemTypeRightCancel:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_CANCEL;
//            break;
//        }
//        case ZKBNavigationItemTypeRightFinish:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_FINISH;
//            break;
//        }
//        case ZKBNavigationItemTypeRightAddProject:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_ADDPROJECT;
//            break;
//        }
//        case ZKBNavigationItemTypeRightPutInBlack:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_PUTINBLACK;
//            break;
//        }
//        case ZKBNavigationItemTypeRightCreateGroup:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_CREATEGROUP;
//            break;
//        }
//        case ZKBNavigationItemTypeRightFeedback:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_FEEDBACK;
//            break;
//        }
//        case ZKBNavigationItemTypeRightAddAlarmClock:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_ADDALARMCLOCK;
//            break;
//        }
//            //        case ZKBNavigationItemTypeRightAddFriend:{
//            //            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_ADDFRIEND;
//            //            break;
//            //        }
//        case ZKBNavigationItemTypeRightSendCooperation:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_SENDCOOPERATION;
//            break;
//        }
//        case ZKBNavigationItemTypeRightSetting:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_SETTING;
//            break;
//        }
//        case ZKBNavigationItemTypeRightNewAdd:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_NEWADD;
//            break;
//        }
//        case ZKBNavigationItemTypeRightMatchmakerSetting:{
//            strTitle = ZKB_NAVIGATION_BAR_TEXT_RIGHT_MATCHMAKERSETTING;
//        }
//        default:{
//            
//            break;
//        }
//    }
//    return strTitle;
//}

//+ (UIImage *)getNavigationBarRightImgByType:(ZKBNavigationItemType)type{
//    UIImage *img = [UIImage getImageWithName:ZKB_NAVIGATION_BAR_RIGHT_BG_IMAGE_NAME];
//    switch (type) {
//        case ZKBNavigationItemTypeRightIcon:{
//            img = [UIImage getImageWithName:ZKB_NAVIGATION_BAR_RIGHT_ICON_BG_IMAGE_NAME];
//            break;
//        }
//        case ZKBNavigationItemTypeRightDoubleIcon:{
//            img = [UIImage getImageWithName:ZKB_NAVIGATION_BAR_RIGHT_DOUBLE_ICON_BG_IMAGE_NAME];
//            break;
//        }
//        case ZKBNavigationItemTypeRightPoint:{
//            img = [UIImage getImageWithName:ZKB_NAVIGATION_BAR_RIGHT_POINT_BG_IMAGE_NAME];
//            break;
//        }
//        case ZKBNavigationItemTypeRightQuestion:{
//            img = [UIImage getImageWithName:ZKB_NAVIGATION_BAR_RIGHT_QUESTION_BG_IMAGE_NAME];
//            break;
//        }
//        case ZKBNavigationItemTypeRightCustomSetting:{
//            img = [UIImage getImageWithName:ZKB_NAVIGATION_BAR_RIGHT_CUSTOMSETTING_BG_IMAGE_NAME];
//            break;
//        }
//        case ZKBNavigationItemTypeRightAdd:{
//            img = [UIImage getImageWithName:ZKB_NAVIGATION_BAR_RIGHT_ADD_BG_IMAGE_NAME];
//            break;
//        }
//        case ZKBNavigationItemTypeRightAddFriend:{
//            img = [UIImage getImageWithName:ZKB_NAVIGATION_BAR_RIGHT_ADD_FRIEND_BG_IMAGE_NAME];
//            break;
//        }
//        case ZKBNavigationItemTypeRightNewProject:
//        case ZKBNavigationItemTypeRightSubscribeProject:
//        case ZKBNavigationItemTypeRightAddProject:
//        case ZKBNavigationItemTypeRightAddAlarmClock:
//        case ZKBNavigationItemTypeRightNext:
//        case ZKBNavigationItemTypeRightSendCooperation:
//        case ZKBNavigationItemTypeRightSetting:
//        case ZKBNavigationItemTypeRightNewAdd:{
//            img = [UIImage getImageWithName:ZKB_NAVIGATION_BAR_RIGHT_BG_IMAGE_NAME];
//            break;
//            
//        }
//        case ZKBNavigationItemTypeRightShare:{
//            img = [UIImage getImageWithName:ZKB_NAVIGATION_BAR_RIGHT_SHARE_BG_IMAGE_NAME];
//            break;
//        }
//        case ZKBNavigationItemTypeRightRead:{
//            img = [UIImage getImageWithName:ZKB_NAVIGATION_BAR_RIGHT_BG_IMAGE_NAME];
//            break;
//        }
//        default:{
//            
//            break;
//        }
//    }
//    return img;
//}

+ (NSDictionary *)getDictionaryByStrJson:(NSString *)strJson{
    if(strJson.length == 0){
        return @{};
    }
    NSData *data = [strJson dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    return dic;
}

+ (NSArray *)getArrByStrJson:(NSString *)strJson{
    if(strJson.length == 0){
        return @[];
    }
    NSData *data = [strJson dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    return arr;
}

+ (NSString *)getStrJsonByDic:(NSDictionary *)dic{
    NSString *strJson = @"";
    
    NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:nil];
    if(data.length > 0){
        strJson = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return strJson;
}

+ (NSString *)getStrJsonByArray:(NSArray *)arr{
    NSString *strJson = @"";
    
    NSData *data = [NSJSONSerialization dataWithJSONObject:arr options:kNilOptions error:nil];
    if(data.length > 0){
        strJson = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return strJson;
}

#define D_TOOLS_QUAKE_KEY       @"quake_key"
#define KVIEW_KEY_DATE          @"error_date"
#define kVIEW_ERROR_SAVE_TIME   86400
+ (void)needQuake{
    NSDictionary *dicError = (NSDictionary *)[DCacheManager getCacheObjectForKey:D_TOOLS_QUAKE_KEY];
    NSMutableDictionary *dic = [NSMutableDictionary new];
    if(dicError){
        NSDate *date = [NSDate date];
        NSDate *lastDate = [dicError objectForKey:KVIEW_KEY_DATE];
        DLog(@"%@",@([date timeIntervalSinceDate:lastDate]));
        if(lastDate && [date timeIntervalSinceDate:lastDate] < 10){
            return;
        }
        
    }
    [dic setObject:[NSDate date] forKey:KVIEW_KEY_DATE];
    [DCacheManager setCacheObjectByData:dic forKey:D_TOOLS_QUAKE_KEY withTimeoutInterval:kVIEW_ERROR_SAVE_TIME];
    
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    DLog(@"Quake");
}

+(DeviceType)getDeviceType

{
    DeviceType type;
    CGRect bounds = [[UIScreen mainScreen] bounds];
    CGFloat height=bounds.size.height;
    CGFloat scale=[UIScreen mainScreen].scale;
    
    if(height < 667){
        type = DeviceTypeFor5SAndAbove;
    }
    else if(scale < 2.9){
        type = DeviceTypeFor6;
    }
    else{
        type = DeviceTypeFor6p;
    }
    return type;
}

//获取聊天最大长度边距
+ (CGFloat)getChatMaxContentSpace{
    CGFloat space = 0;
    DeviceType type = [DCommonTool getDeviceType];
    switch (type) {
        case DeviceTypeFor5SAndAbove:{
            
            break;
        }
        case DeviceTypeFor6:{
            space = 20;
            break;
        }
        case DeviceTypeFor6p:{
            space = 30;
            break;
        }
        default:
            break;
    }
    return space;
}

//获取
+ (CGFloat)getSubViewWidth:(CGFloat)width{
    CGFloat newWidth = width;
    DeviceType type = [DCommonTool getDeviceType];
    switch (type) {
        case DeviceTypeFor5SAndAbove:{
            
            break;
        }
        case DeviceTypeFor6:{
            
            break;
        }
        case DeviceTypeFor6p:{
            newWidth *= 0.84;
            break;
        }
        default:
            break;
    }
    return newWidth;
}

+ (CGFloat)getSubViewHeight:(CGFloat)height{
    CGFloat newHeight = height;
    DeviceType type = [DCommonTool getDeviceType];
    switch (type) {
        case DeviceTypeFor5SAndAbove:{
            
            break;
        }
        case DeviceTypeFor6:{
            
            break;
        }
        case DeviceTypeFor6p:{
            newHeight *= 0.84;
            break;
        }
        default:
            break;
    }
    return newHeight;
}

//获取文本内容是否含有电话号码
+ (NSMutableArray *)getMobileByStr:(NSString *)strContent
{
    NSMutableArray *arrUrl = [NSMutableArray array];
    if(strContent && strContent.length > 0)
    {
        NSString *regulaStr = @"\\d{7,23}";
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                               options:NSRegularExpressionCaseInsensitive error:nil];
        
        NSArray *arrayOfAllMatches = [regex matchesInString:strContent
                                                    options:0
                                                      range:NSMakeRange(0, [strContent length])];
        
        for (NSTextCheckingResult *match in arrayOfAllMatches)
        {
            NSString* substringForMatch = [strContent substringWithRange:match.range];
            [arrUrl addObject:substringForMatch];
        }
    }
    return arrUrl;
}

//获取并解析button/json内容
//+ (NSString *)getButtonJsonContentByStr:(NSString *)strContent
//{
//    NSString *strReturn = @"";
//    NSMutableArray *arrUrl = [NSMutableArray array];
//    
//    NSMutableArray *arrKeyword = [NSMutableArray new];
//    NSMutableArray *arrBGImage = [NSMutableArray new];
//    
//    if(strContent.length > 0){
//        NSDictionary *dicContent = [DCommonTool getDictionaryByStrJson:strContent];
//        
//        NSArray *arrButton = @[];
//        DicHasKeyAndDo(dicContent, @"buttons", arrButton = [dicContent objectForKey:@"buttons"];);
//        for (NSDictionary *dicButton in arrButton.objectEnumerator) {
//            @autoreleasepool {
//                NSString *url = @"";
//                DicHasKeyAndDo(dicButton, @"href", url = [dicButton objectForKey:@"href"];);
//                NSString *keyword = @"";
//                DicHasKeyAndDo(dicButton, @"title", keyword = [dicButton objectForKey:@"title"];);
//                if(url.length > 0 && keyword.length > 0){
//                    NSArray *arrSubUrl = [url componentsSeparatedByString:@"?"];
//                    if(arrSubUrl.count == 2){
//                        NSString *strSender = [arrSubUrl objectAtIndex:1];
//                        if([strSender hasPrefix:@"sender="]){
//                            long long uid = [[strSender stringByReplacingOccurrencesOfString:@"sender=" withString:@""] integerValue];
//                            if(uid != KGLOBALINFOMANAGER.uid){
//                                url = [arrSubUrl objectAtIndex:0];
//                                [arrUrl addObject:url];
//                                [arrKeyword addObject:keyword];
//                                [arrBGImage addObject:@"login_btn_login"];
//                            }
//                        }
//                        else{
//                            [arrUrl addObject:url];
//                            [arrKeyword addObject:keyword];
//                            [arrBGImage addObject:@"login_btn_login"];
//                        }
//                    }
//                    
//                }
//            }
//        }
//        
//        NSString *strMsgContent = [dicContent objectForKey:@"content"];
//        
//        NSDictionary *dicMsgContent = @{kParamContent:ExistStringGet(strMsgContent),
//                                        kParamKeywords:arrKeyword,
//                                        kParamKeywordColor:@(TGColorForWhite),
//                                        kParamKeywordLink:arrUrl,
//                                        kParamKeywordBGImage:arrBGImage};
//        strReturn = [ZKBTools getStrJsonByDic:dicMsgContent];
//    }
//    
//    
//    
//    return strReturn;
//}




+ (NSString *)intToBinary:(int)intValue{
    int byteBlock = 8,    // 每个字节8位
    totalBits = sizeof(int) * byteBlock, // 总位数（不写死，可以适应变化）
    binaryDigit = 1;  // 当前掩（masked）位
    NSMutableString *binaryStr = [[NSMutableString alloc] init];   // 二进制字串
    do
    {
        // 检出下一位，然后向左移位，附加 0 或 1
        [binaryStr insertString:((intValue & binaryDigit) ? @"1" : @"0" ) atIndex:0];
        // 若还有待处理的位（目的是为避免在最后加上分界符），且正处于字节边界，则加入分界符|
        if (--totalBits && !(totalBits % byteBlock))
            [binaryStr insertString:@"|" atIndex:0];
        // 移到下一位
        binaryDigit <<= 1;
    } while (totalBits);
    // 返回二进制字串
    return binaryStr;
}

@end
